﻿using Microsoft.AspNetCore.Authentication.JwtBearer;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.IdentityModel.Tokens;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;

namespace EWms.Core.Components
{
    public static class JwtSetup
    {
        public static void AddJwt(this IServiceCollection services)
        {
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
            }).AddJwtBearer(o =>
            {
                o.TokenValidationParameters = new TokenValidationParameters
                {
                    // 是否开启签名认证
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.Jwt.SecretKey)),
                    // 发行人验证
                    ValidateIssuer = true,
                    // 接收人验证
                    ValidateAudience = true,
                    ValidIssuer = AppSettings.Jwt.Issuer, //发行人
                    ValidAudience = AppSettings.Jwt.Audience, //订阅人
                    ValidateLifetime = true,
                    ClockSkew = TimeSpan.Zero,
                };
            });
        }
        /// <summary>
        /// 生成JWT
        /// </summary>
        /// <param name="user">用户信息建议加密</param>
        /// <param name="expiresMinuteTime">过期时间</param>
        /// <returns></returns>
        public static string GetJWT(string user, long? expiresMinuteTime = null)
        {
            if (expiresMinuteTime == null)
            {
                expiresMinuteTime = AppSettings.Jwt.ExpiresMinuteTime;
            }
            List<Claim> claims = new List<Claim>
            {
                new Claim("jti", user),
                new Claim("iat", $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim("nbf", $"{new DateTimeOffset(DateTime.Now).ToUnixTimeSeconds()}"),
                new Claim("exp", $"{new DateTimeOffset(DateTime.Now.AddSeconds(expiresMinuteTime.Value * 216000)).ToUnixTimeSeconds()}"),
                new Claim("iss", AppSettings.Jwt.Issuer),
                new Claim("aud", AppSettings.Jwt.Audience)
            };
            SymmetricSecurityKey key = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(AppSettings.Jwt.SecretKey));
            SigningCredentials signingCredentials = new SigningCredentials(key, "HS256");
            SigningCredentials signingCredentials2 = signingCredentials;
            JwtSecurityToken token = new JwtSecurityToken(null, null, claims, null, null, signingCredentials2);
            JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            return jwtSecurityTokenHandler.WriteToken(token);
        }
        public static string ReadJwtToken(string token)
        {
            JwtSecurityTokenHandler jwtSecurityTokenHandler = new JwtSecurityTokenHandler();
            return jwtSecurityTokenHandler.ReadJwtToken(token).Id;
        }
    }
}
